﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using FineUI;
using SDLITS.Model;
using SDLITS.Common;
using System.Data;
using System.Data.SqlClient;

namespace SDLITS.Web.Driver
{
    public partial class CardRechargeManage : CommonBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!IsPostBack && Request.QueryString["cardNo"] != null)
                {
                    txtMemCardNo.Text = Request.QueryString["cardNo"];
                    if (Request.QueryString["init"] != null && !string.IsNullOrEmpty(Request.QueryString["init"]))
                    {
                        Panel8.Hidden = false;
                        btnSaveRefresh.Hidden = false;
                        txt_bkfy.Text = Request.QueryString["init"];
                        txtMemCardNo.Enabled = false;
                        txt_bkfy.Enabled = false;
                        txt_bksxf.Enabled = false;
                    }
                    if (Request.QueryString["work"] != null && !string.IsNullOrEmpty(Request.QueryString["work"]))
                    {
                        txt_bksxf.Text = Request.QueryString["work"];
                    }
                    BindData();
                    CalcTotal();
                }
            }
        }
        protected bool BindData()
        {

            V_MemCardInfoType item = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == txtMemCardNo.Text.Trim()).ToFirstDefault();
            if (item != null)
            {
                if (!item.LeftCash.HasValue)
                {
                    SDDbSession.Default.FromSql("update MemCard set LeftCash=0,LeftTimes=0 where MemcardNo='" + txtMemCardNo.Text + "'").ExecuteNonQuery();
                }
                txt_type.Text = item.MemType;
                txt_start.Text = item.StartDate.ToString();
                txt_end.Text = item.ExpireDate.ToString();
                txt_cash.Text = item.LeftCash.ToString();

                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@MemTypeID",item.MemTypeID),
                    new SqlParameter("@SPAction","SelectAllByMemTypeID")
                };
                DataSet ds = SDDbSession.Default.FromProc("TableBounsPlan").AddParameter(sp).ToDataSet();
                if (ds != null & ds.Tables.Count > 0)
                {
                    taocanGrid.DataSource = ds;
                    taocanGrid.DataBind();
                    taocanGrid.Hidden = false;
                    //drp_taocan.Items.Clear();
                    //ListItem li = new ListItem("无套餐", "0|0|0");
                    //drp_taocan.Items.Add(li);
                    //drp_taocan.Items[0].Selected = true;
                    //for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    //{
                    //    ListItem lis = new ListItem(ds.Tables[0].Rows[i]["Text"].ToString(), ds.Tables[0].Rows[i]["Value"].ToString());
                    //    drp_taocan.Items.Add(lis);
                    //}
                    //  drp_taocan.Hidden = false;
                }
                else
                {
                    taocanGrid.Hidden = true;
                    // drp_taocan.Hidden = true;
                }
                return true;
            }
            return false;
        }
        protected void btnSaveRefresh_Click(object sender, EventArgs e)
        {
            int l = taocanGrid.SelectedRowIndexArray.Length;

            if (l > 0 || Convert.ToDecimal(txt_pay.Text.Trim()) != 0)
            {
              string values=  taocanGrid.Rows[taocanGrid.SelectedRowIndex].Values[1].ToString();
                decimal plusAmount = 0;
                if (!string.IsNullOrEmpty(txt_pay.Text.Trim()))
                {
                    plusAmount = Convert.ToDecimal(txt_pay.Text);
                }
                decimal bonseAmount = 0;

                DateTime dtNewExpire = DateTime.Now;
                if ((Convert.ToDateTime(txt_end.Text)) > dtNewExpire)
                {
                    dtNewExpire = (Convert.ToDateTime(txt_end.Text));
                }

                int plusDays = Convert.ToInt32(dtNewExpire.Subtract(DateTime.Today).Days);
                int plusDays2Log = 0;
                int plusTimes = 0;
                if (values != "")
                {
                    string[] times = values.Split('|');
                    bonseAmount = Convert.ToDecimal(times[0]);
                    plusDays = Convert.ToInt32(times[1]) + plusDays;
                    plusTimes = Convert.ToInt32(times[2]);
                    plusDays2Log = Convert.ToInt32(times[1]);
                }
                ModelLoginUser user = Session["LoginUser"] as ModelLoginUser;
                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@BonusAmount",bonseAmount),
                    new SqlParameter("@PlusDays",plusDays),
                    new SqlParameter("@PlusTimes",plusTimes),
                    new SqlParameter("@PlusAmount",plusAmount),
                    new SqlParameter("@CreateUserID",user.UserID),
                    new SqlParameter("@MemcardNo",txtMemCardNo.Text.Trim()),
                    new SqlParameter("@PlusDays2Log",plusDays2Log),
                    new SqlParameter("@SPAction","Recharge")
                };
                SDDbSession.Default.FromProc("TableCardRevenue").AddParameter(sp).ExecuteNonQuery();
                //if (result <= 0)
                //{
                //    Alert.Show("充值失败，请返回重试！");
                //    return;
                //}
                Print();

                BindData();
                Alert.Show("出入卡充值成功！");
                ClearControl();
                btnSaveRefresh.Hidden = true;
                Response.Redirect("/Driver/AllCardManage.aspx");
            }
            else
            {
                Alert.Show("充值金额为 0！");
            }
        }
        private void Print()
        {
            SetPrintSession();
            PageContext.RegisterStartupScript(Window1.GetShowReference("CardRechargePrint.aspx", "打印办卡记录"));
        }

        private void SetPrintSession()
        {

            string values = taocanGrid.Rows[taocanGrid.SelectedRowIndex].Values[1].ToString();
            string[] bPlans = values.Split('|');
            string bPlan = string.Format("{0}元 {1}天", bPlans[0], bPlans[1]);

            V_MemCardInfoType item = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == txtMemCardNo.Text.Trim()).ToFirstDefault();
            ModelLoginUser user = Session["LoginUser"] as ModelLoginUser;
            if (item != null)
            {
                var mrp = new ModelCardRechargePrint
                {
                    MemType = txt_type.Text,
                    StartDate = item.StartDate.ToString(),
                    ExpireDate = item.ExpireDate.ToString(),
                    InitialAmount = txt_bkfy.Text,
                    WorkAmount = txt_bksxf.Text,
                    BonusType = bPlan,
                    PlusAmount = string.Format("{0:N}", Convert.ToInt32(txt_pay.Text)),
                    Worker = user.RealName,
                    MemCardNo = txtMemCardNo.Text,
                    Total = txt_total.Text,
                };
                Session["CardRechargePrint"] = mrp;
            }
        }
        protected void drp_taocan_SelectedIndexChanged(object sender, EventArgs e)
        {
            CalcTotal();
        }
        private void CalcTotal()
        {
            decimal initialAmount = 0;
            if (!string.IsNullOrEmpty(txt_bkfy.Text))
            {
                decimal.TryParse(txt_bkfy.Text, out initialAmount);
            }
            decimal workAmount = 0;
            if (!string.IsNullOrEmpty(txt_bksxf.Text))
            {
                decimal.TryParse(txt_bksxf.Text, out workAmount);
            }
            decimal bPlanAmount = 0;
            if (taocanGrid.SelectedRowIndexArray.Length > 0)
            {
                string values = taocanGrid.Rows[taocanGrid.SelectedRowIndex].Values[1].ToString();
                if (!string.IsNullOrEmpty(values))
                {
                    bPlanAmount = Convert.ToDecimal(values.Split('|')[0]);
                    hidplan.Text = bPlanAmount.ToString();
                }
            }
            decimal plusAmount = 0;
            if (!string.IsNullOrEmpty(txt_pay.Text))
            {
                decimal.TryParse(txt_pay.Text, out plusAmount);
            }
            txt_total.Text = (initialAmount + workAmount + bPlanAmount + plusAmount).ToString();
        }

        protected void txtMemCardNo_TextChanged(object sender, EventArgs e)
        {
            ClearControl();
            if (BindData())
            {
                CalcTotal();
                btnSaveRefresh.Hidden = false;
            }
            else
            {
                btnSaveRefresh.Hidden = true;
                Alert.Show("请检查出入卡号！");
            }
        }
        private void ClearControl()
        {
            txt_type.Text = "";
            txt_start.Text = "";
            txt_end.Text = "";
            txt_cash.Text = "";

            txt_bkfy.Text = "0.00";
            txt_bksxf.Text = "0.00";
            txt_pay.Text = "0.00";
            txt_total.Text = "0.00";
            hidplan.Text = "0.00";
            // txtMemCardNo.Text = "";

            btnSaveRefresh.Hidden = true;
            drp_taocan.Items.Clear();
        }

        protected void txt_pay_TextChanged(object sender, EventArgs e)
        {
            CalcTotal();
        }

        protected void taocanGrid_RowSelect(object sender, GridRowSelectEventArgs e)
        {
            CalcTotal();
        }
    }
    public class ModelCardRechargePrint
    {
        public string StartDate { get; set; }
        public string ExpireDate { get; set; }
        public string MemType { get; set; }
        public string WorkAmount { get; set; }
        public string InitialAmount { get; set; }
        public string BonusType { get; set; }
        public string PlusAmount { get; set; }
        public string Total { get; set; }
        public string Worker { get; set; }
        public string MemCardNo { get; set; }
    }
}